import { BasePlatform } from '../BasePlatform';
import { _platform } from '../../Main';

export class TT extends BasePlatform {

    sceneEnable: boolean = false

    gridGamePanel: any = null

    titles = [
        '人生在世无非吃喝二字'
    ]

    descs = [
        '来喂饱小吗喽们吧'
    ]

    adparams = {
        adid: undefined,
        clickid: undefined,
        creativeid: undefined,
        creativetype: undefined
    }
    
    constructor(id: string = '', key: string = '', video: string[] = [], banner: string[] = [], interstitial: string[] = [], custom: string[] = []) {
        super(window['tt'], id, key, video, banner, interstitial, custom)
        console.log('抖音平台加载完毕')
    }

    init(): void {
        this.loadLauncuOptions()
        this.checkScene()
        this.createGridGamePanel()
    }

    loadLauncuOptions() {
        let launchOptions = this.platform.getLaunchOptionsSync()
        let adparams = launchOptions.query.ad_params
        if (!adparams) {
            return
        }
        for (let key in this.adparams) {
            this.adparams[key] = launchOptions.query[key]
        }
        console.log(this.adparams)
    }

    postEvent(event_type: string, properties = {}) {
        if (!this.adparams.clickid) {
            return
        }
        let data = {
            "event_type": event_type, 
            "context": {
                "ad": {
                    "callback": this.adparams.clickid,
                }
            },
            "properties": properties,
            "timestamp": Date.now()
        }
        fetch('https://analytics.oceanengine.com/api/v2/conversion', {
            method: 'POST',
            headers: {  
                'Content-Type': 'application/json',
            }, 
            body: JSON.stringify(data)
        })
        .then(res => {
            if (!res.ok) {
                throw new Error('Network response was not ok')
            }
            return res.json()
        })
        .then(data => {
            console.log('Post Success: ', data)
        })
        .catch((error) => {
            console.error('Post Error: ', error)
        })
    }

    isTiktok() {
        if (!this.systemInfo) {
            return false
        }
        let appName: string = this.systemInfo.appName
        appName = appName.toUpperCase()
        return appName == 'DOUYIN' || appName == 'DOUYIN_LITE'
    }

    login(callback?: (success: boolean) => void): void {
        this.platform.login({
            force: true,
            success(res) {
                console.log(`login 调用成功${res.code} ${res.anonymousCode}`)
                if (callback) {
                    callback(true)
                }
            },
            fail(res) {
                console.log(`login 调用失败`)
                if (callback) {
                    callback(false)
                }
            },
        })
    }

    /**
     * 分享
     * @param callback 回调函数
     * @param channel 分享方式
     */
    share(callback?: (success: boolean) => void, channel?: string): void {
        this.shareAppMessage([], callback, channel)
    }

    shareAppMessage(videoTopics = [], callback?: (success: boolean) => void, channel?: string) {
        console.log('share ' + this.recorderHandler.videoPath)
        let recorder = this.recorderHandler
        let c = channel ? channel : "video"
        let extra = {}
        if (c == 'video') {
            if (recorder.recording == true) {
                //分享出错
                if (callback)
                    callback(false)
                return;
            }
            if (recorder.videoPath === '') {
                if (callback)
                    callback(false)
                recorder.getVideo = true
                return
            }
            console.log("开始分享", recorder.videoPath)
            extra = {
                videoPath: recorder.videoPath,
                videoTopics,
                withVideoId: true,
            }
            console.log("extra", extra)
        }
        console.log(this.platform)
        this.platform.shareAppMessage({
            title: this.titles[0],
            desc: this.descs[0],
            channel: c,
            extra: extra,
            success(res) {
                console.log("分享成功", res)
                if (callback)
                    callback(true)
            },
            fail(e) {
                if (e.errMsg == "shareAppMessage:cancel" || e.errMsg == "shareAppMessage:fail cancel" 
                    || e.errMsg == "shareAppMessage:fail internal error Share error") {
                    console.log("分享失败", e)
                    if (c == 'invite') {
                        //邀请失败
                    } else if (c == 'video') {
                        //分享视频失败
                    } else if (c == 'token') {
                        //分享口令失败
                    }
                } else {
                    if (e.errMsg == 'shareAppMessage:fail Internal error: unsupport share type in host') {
                        if (callback) {
                            callback(true)
                        }
                    } else {
                        console.log("分享视频失败", e)
                        //录屏时间少于3秒
                    }
                }
            },
        })
    }

    /** 检测是否支持侧边栏 */
    checkScene() {
        this.platform.checkScene({
            scene: "sidebar",
            success: (res) => {
                this.sceneEnable = true
                console.log("check scene success: ", res.isExist);
                //成功回调逻辑
            },
            fail: (res) => {
                this.sceneEnable = true
                console.log("check scene fail:", res);
                //失败回调逻辑
            }
        });
    }

    /** 导航至侧边栏 */
    navigateToScene() {
        this.platform.navigateToScene({
            scene: "sidebar",
            success: (res) => {
                console.log("navigate to scene success")
            },
            fail: (res) => {
                console.log("navigate to scene fail: ", res)
            },
        })
    }

    createGridGamePanel(count: 'one' | 'four' | 'nine' = 'four', size: 'large' | 'mediun' | 'small' = 'large', position: { left: number, top: number } = { left: 600, top: 300 }, query = {}) {
        this.gridGamePanel = this.platform.createGridGamePanel({
            gridCount: count,
            size: size,
            position: position,
            query: query
        })
    }

    showGridGamePanel() {
        if (!this.gridGamePanel) {
            return
        }
        this.gridGamePanel.show()
    }

    hideGridGamePanel() {
        if (!this.gridGamePanel) {
            return
        }
        this.gridGamePanel.hide()
    }

    /**
     * 设置抖音默认排行数据
     * @param value 值
     * @param dataType 0为数字，1为字符串
     * @param priority 字符串类型必填，权重，越大显示越靠前
     * @param extra 额外字段
     * @param zoneId 分区标识
     */
    setImRankData(value: string, dataType: 0 | 1, priority: number = 0, extra: string = '', zoneId: string = 'default') {
        this.platform.setImRankData({
            dataType: dataType,
            value: value,
            priority: priority,
            extra: extra,
            zoneId: zoneId,
            success(res) {
                console.log(`setImRankData success res: ${res}`)
            },
            fail(res) {
                console.log(`setImRankData fail res: ${res.errMsg}`)
            },
        })
    }

    /**
     * 打开抖音默认排行榜
     * @param relationType 关系类型
     * @param dataType 0为数字，1为字符串
     * @param rankType 日期类型
     * @param rankTitle 标题
     * @param suffix 后缀
     * @param zoneId 分区标识
     */
    getImRankList(relationType: 'default' | 'friend' | 'all' = 'default', dataType: 0 | 1 = 1, 
        rankType: 'day' | 'week' | 'month' | 'all' = 'all', rankTitle: string = '', suffix: string = '', zoneId: string = 'default') {
        this.login((success) => {
            if (success) {
                this.platform.getImRankList({
                    relationType: relationType,
                    dataType: dataType,
                    rankType: rankType,
                    suffix: suffix,
                    rankTitle: rankTitle,
                    zoneId: zoneId,
                    success(res) {
                        console.log(`getImRankData success res: ${res}`)
                    },
                    fail(res) {
                        console.log(`getImRankData fail res: ${res.errMsg}`)
                    },
                })
            }
        })
    }
}


